package com.amway.qy.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.core.constants.QyWechatUrls;
import com.amway.qy.core.service.QyAccessTokenService;
import com.amway.qy.core.service.QyWechatAuthService;
import com.amway.qy.util.common.QyHttpClientUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class QyWechatAuthServiceImpl implements QyWechatAuthService {

	private static final Logger logger = LoggerFactory.getLogger(QyWechatAuthServiceImpl.class);
	
	private QyAccessTokenService accessTokenManager;
	
	// Construct here
	public QyWechatAuthServiceImpl(QyAccessTokenService accessTokenManager) {
		this.accessTokenManager = accessTokenManager;
	}
	@Override
	public QyAccessTokenService getQyAccessTokenService() {
		return accessTokenManager;
	}

	@Override
	public void setQyAccessTokenService(QyAccessTokenService tokenService) {
		this.accessTokenManager = tokenService;
	}

	@Override
	public String getUserByAuthCode(String code) {
//		String get_userid_url = MessageFormat.format(QyWechatUrls.getuseridurl, new Object[]{accessTokenManager.getAccessToken(),code});
		/* 根据用户统一验证登录返回来的code获取用户的userid */
		List<NameValuePair> paramList = getAccessTokenList();
		paramList.add(new BasicNameValuePair("code", code));
		String userIdInfo =  QyHttpClientUtils.httpsGet(QyWechatUrls.GET_USERID_URL, paramList);
		JsonObject userObj = new JsonParser().parse(userIdInfo).getAsJsonObject();
		logger.info("get userid info is >> " + userObj.toString());
		String userId;
		/* 如果用户存在userid则需要用userid去取回openid，因为后面需要用它来参与到支付或是其它操作 */
		if (userObj.has("UserId")){

			userId = userObj.get("UserId").getAsString();
		} else {
			/* 如果不存在则直接返回带有openid的用户信息 */
			return userObj.toString();
		}
		
		String openIdReqData = "{\"userid\": \"" + userId + "\"}";
		/* 在用户只有userid的情况下，取出用户的openid拼接上和其它企业号相关信息一起拼接返回来 */
//		String userid2openidURL_full = MessageFormat.format(QyWechatUrls.userid2openid, new Object[]{accessTokenManager.getAccessToken()});
		
		String openidJson = QyHttpClientUtils.httpsPostJson(QyWechatUrls.USERID2OPENID, getAccessTokenList(), openIdReqData);
		
		JsonObject openidOjb = new JsonParser().parse(openidJson).getAsJsonObject();
		
		String OpenId = openidOjb.get("openid").getAsString();
		
		userObj.addProperty("OpenId", OpenId);
		logger.info("get qywechat info is >> " + userObj.toString());
		return userObj.toString();
	}

	private List<NameValuePair> getAccessTokenList(){
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		paramList.add(new BasicNameValuePair("access_token", accessTokenManager.getAccessToken()));
		return paramList;
	}
}
